<template>
  <BasicDrawer @register="registerDrawer" width="800px" :isDetail="true" :showDetailBack="false">
    <Row :gutter="[24, 24]">
      <Col :span="6" v-for="item in widgetsPackage" :key="item.id.id">
        <Card
          :title="item.name"
          :hoverable="true"
          :bodyStyle="{ padding: '0' }"
          @click="handleSelect(item)"
        >
          <Image
            class="!w-48 !h-32 object-contain"
            :preview="false"
            :src="item.image ? item.image : imageUrl"
          />
        </Card>
      </Col>
    </Row>
    <WidgetsDrawer @register="register" :level="level" @add="handleAdd" />
  </BasicDrawer>
</template>

<script lang="ts" setup name="WidgetsDrawer">
  import { onMounted, ref, computed } from 'vue';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';
  import {
    getCommentTable,
    getBundleWidgetTypeInfos,
  } from '/@/api/thingsborad/resources/widgets/widgets';
  import { Row, Col, Card, Image } from 'ant-design-vue';

  const props = defineProps({
    level: {
      type: Number,
      default: 1,
      required: false,
    },
  });
  const imageUrl = computed(() => {
    return `http://${import.meta.env.VITE_IP_PORT}/assets/widget-preview-empty.svg`;
  });
  const emits = defineEmits(['add']);
  const widgetsPackage = ref<any[]>([]);
  const level = ref<number>(1);
  const [register, { openDrawer }] = useDrawer();
  const [registerDrawer, { setDrawerProps, closeDrawer: closePackageDrawer }] = useDrawerInner(
    async (packageId) => {
      if (props.level == 1) {
        setDrawerProps({
          title: '选择部件包',
          headerStyle: {
            'padding-left': '12px',
          },
        });
        const { data } = await getCommentTable({
          pageSize: 100,
          page: 0,
          sortProperty: 'title',
          sortOrder: 'ASC',
          tenantOnly: false,
          fullSearch: true,
        });
        widgetsPackage.value = data;
      } else if (props.level == 2) {
        setDrawerProps({
          title: '选择部件',
          headerStyle: {
            'padding-left': '12px',
          },
        });
        const { data } = await getBundleWidgetTypeInfos({
          pageSize: 28,
          page: 0,
          sortProperty: name,
          sortOrder: 'ASC',
          widgetsBundleId: packageId,
          fullSearch: true,
          deprecatedFilter: 'ACTUAL',
        });
        widgetsPackage.value = data;
      }
    },
  );
  const handleSelect = (item: any) => {
    if (props.level == 1) {
      level.value = 2;
      closePackageDrawer();
      openDrawer(true, item.id.id);
    } else {
      closePackageDrawer();
      emits('add', item);
    }
  };
  const handleAdd = (item) => {
    emits('add', item);
  };

  onMounted(async () => {});
</script>
